import {Upload, Button, Icon, Modal} from 'antd';
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import classnames from 'classnames'
import ImageService from './imageService'
import qs from 'qs'
import urlencode from 'urlencode'

export default class LwjUploadPic extends Component {
  state = {
    previewVisible: false,
    previewImage: '',
    fileList: []
  };

  handleCancel = () => this.setState({previewVisible: false})

  handlePreview = (file) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true
    });
  }

  handleChange = ({fileList}) => {
    this.setState({fileList});
  }

  componentDidMount() {
    // 元处理方式
    if (this.props.fileLists) {
      let picUrlsAAA = this.props.fileLists;
      const getUrlAAA = (picUrls) => {
        let promiseArr = [];
        const IMAGE_THUMBNAIL_PARAM_ALIOSS = '?x-oss-process=image/resize,m_lfit,h_400,w_400';
        if (picUrls && picUrls.split(';').length > 0) {
          let newpicUrls = picUrls.split(';');
          if (newpicUrls[newpicUrls.length - 1] == "") {
            newpicUrls.pop();
          }
          newpicUrls.map(img => {
              promiseArr.push(new Promise(function (resolve, reject) {
                ImageService.show(img, (imgUrl) => {
                  let thumbnail = '';
                  if (imgUrl) {
                    thumbnail = imgUrl.split('?')[0] + IMAGE_THUMBNAIL_PARAM_ALIOSS;
                  }
                  resolve({url: imgUrl, thumbnail: thumbnail, orginUrl: img});
                });
              }));
            });
          return promiseArr;
        }
      }
      const dealedTargetUrlAAA = getUrlAAA(picUrlsAAA);
      let sureDealedUrlAAA = [];
      dealedTargetUrlAAA.forEach((value, index) => {
        value.then((val) => {
          const name = urlencode.decode(qs.parse(val.url)['response-content-disposition'], 'utf-8')
          const tname = name.slice(name.indexOf("filename*=UTF-8") + 17)
          sureDealedUrlAAA.push({
            name: tname,
            uid: index,
            url: val.url,
            response: {
              result: val.orginUrl
            }
          });
          this.setState({fileList: sureDealedUrlAAA});
        })
      })
    }
  }

  render() {

    const {
      maxfile ,
      target,
      onChange
    } = this.props;

    const {previewVisible, previewImage, fileList} = this.state;

    const uploadButton = (
      <div>
        <Icon type="plus"/>
        <div className="ant-upload-text">Upload</div>
      </div>
    );

    const preChange = ({fileList}) => {
      this.setState({fileList});
      // 与处理数据
      let targetValue = '';
      for (let i = 0; i < fileList.length; i++) {
        if (fileList[i].response) {
          targetValue += fileList[i].response.result + ';';
        }
      }
      targetValue = targetValue.substring(0, targetValue.length - 1);
      onChange(targetValue);
    }
    return (
      <div className="clearfix">
        <Upload
          action={target}
          listType="picture-card"
          fileList={fileList}
          onPreview={this.handlePreview}
          onChange={preChange}>
          {fileList.length >= maxfile
            ? null
            : uploadButton}
        </Upload>
        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
          <img
            alt="example"
            style={{
            width: '100%'
          }}
            src={previewImage}/>
        </Modal>
      </div>
    );
  }
}

LwjUploadPic.props = {
  maxfile: PropTypes.number,
  target: PropTypes.string.isRequired,
  change: PropTypes.func,
  fileLists: PropTypes.string
}
